package com.alumni_circle.core.utils;

import io.jsonwebtoken.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author weiqi:
 * @version 创建时间：2018年11月5日 下午9:23:01 登录Token的生成和解析
 */
@Component
public class JwtUtils {

    private String secretKey = "long";

    private Logger logger = LoggerFactory.getLogger(getClass().getName());

    /**
     * 加密
     * @return
     */
    public String encryption(String key,String role){
        long now=System.currentTimeMillis();
        //一天,数字单位为毫秒
        long exp=now+86400000;
        //        System.out.println(token);
        return Jwts.builder()
                //签发时间
                .setIssuedAt( new Date() )
                //角色
                .claim("role",role)
                //过期时间
                .setExpiration( new Date(exp) )
                //其他
                .setSubject(key)

                //加密秘钥、类型
                .signWith(SignatureAlgorithm.HS256, secretKey)
                //压缩为xx.xx.xx格式
                .compact();
    }

    /**
     * 解密
     * @param token
     * @return
     */
    public Map validateToken(String token){
        Map<String,String> map = new HashMap<>();
        try {
            //通过密钥验证Token
            Claims claims = Jwts.parser()
                    .setSigningKey(secretKey)
                    .parseClaimsJws(token)
                    .getBody();
            //获取此token中的角色和Redis键

            map.put("key",claims.getSubject());
            logger.info(claims.getSubject());
            map.put("role",claims.get("role").toString());
            logger.info(claims.get("role").toString());
            logger.info("解密成功");
            return map;
        }catch (SignatureException e) {
            //签名异常
            logger.info("签名异常");
        } catch (MalformedJwtException e) {
            //JWT格式错误
            logger.info("JWT格式错误");
        } catch (ExpiredJwtException e) {
            //JWT过期
            logger.info("JWT过期");
        } catch (UnsupportedJwtException e) {
            //不支持该JWT
            logger.info("不支持该JWT");
        } catch (IllegalArgumentException e) {
            //参数错误异常
            logger.info("参数错误异常");
        }
        return new HashMap<>();
    }

    /**
     * 获取用户权限
     * @param token
     * @return
     */
    public Authentication getAuthentication(String token){
        System.out.println("token:"+token);
        //解析Token的payload
        Claims claims = Jwts.parser()
                .setSigningKey("long")
                .parseClaimsJws(token)
                .getBody();
        Collection<? extends GrantedAuthority> authorities =Arrays.stream(claims.get("authorities")
                                                            //获取用户权限字符串
                                                            .toString().split(","))
                                                            .map(SimpleGrantedAuthority::new)
                                                            //将元素转换为GrantedAuthority接口集合
                                                            .collect(Collectors.toList());
        User principal = new User(claims.getSubject(), "", authorities);
        return new UsernamePasswordAuthenticationToken(principal, "", authorities);
    }
}